package com.mfoyou.agent.web.controller.file;

import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.file.FileService;
import com.mfoyou.agent.web.service.session.SessionService;
import org.apache.commons.lang3.StringUtils;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.mfoyou.agent.common.dao.domain.HuawuFile;
import org.mfoyou.agent.common.entity.MfoyouFileRet;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Path("/file")
@Service
public class FileController {

    @Autowired
    private FileService fileService;
    @Autowired
    SessionService sessionService;
    @Value("#{settings['image_server']}")
    private String image_server;
    @Value("#{settings['file_path']}")
    private String file_path;

    Logger logger = new Logger(FileController.class);

    @POST
    @Path(value = "/upload")
    @Produces("application/json;charset=UTF-8")
    @Consumes("multipart/form-data")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> uploadFile(@Context HttpServletRequest request, MultipartFormDataInput input) {
        try {
            List<HuawuFile> list = fileService.uploadFile(request, input);
            List<String> list1 = new ArrayList<>();
            for (HuawuFile huawuFile : list) {
                list1.add(huawuFile.getFilePath());
            }
            return JsonRet.buildSuccRet(list1);
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
        }
        return JsonRet.buildFailRet("上传失败");
    }

    @POST
    @Path(value = "/uploadToOffice")
    @Produces("application/json;charset=UTF-8")
    @Consumes("multipart/form-data")
    @UrlRight(UserRight.ALLACCESS)
    public HashMap<String, String> uploadToOffice(@Context HttpServletRequest request, MultipartFormDataInput input) {
        try {
            List<HuawuFile> list = fileService.uploadFile(request, input);
            HashMap<String, String> hashMap = new HashMap<>(2, 1);
            hashMap.put("link", image_server + list.get(0).getFilePath());
            return hashMap;
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
        }
        return null;
    }

    @POST
    @Path(value = "/uploadCert")
    @Produces("application/json;charset=UTF-8")
    @Consumes("multipart/form-data")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> uploadCert(@Context HttpServletRequest request, MultipartFormDataInput input,
                                 @QueryParam("userId") Integer userId) {
        boolean checkOldSession = sessionService.checkOldSession(request);
        if (!checkOldSession) {
            return JsonRet.buildRet(-18);
        }
        if (userId == null) {
            return JsonRet.buildRet(-96);
        }
        try {
            List<HuawuFile> list = fileService.uploadFileV2(request, input, userId);
            MfoyouFileRet mfoyouFileRet = new MfoyouFileRet();
            mfoyouFileRet.setList(list);
            mfoyouFileRet.setBasUrl(image_server);
            return JsonRet.buildSuccRet(mfoyouFileRet);
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
        }
        return JsonRet.buildFailRet("上传失败");
    }

    @GET
    @Path(value = "/getFileList")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> getFileList(@Context HttpServletRequest request, @QueryParam("model") Integer model) {
        if (model == null) {
            return JsonRet.buildRet(-96);
        }
        Integer currentUserId = sessionService.currentUserId(request);
        List<HuawuFile> files = fileService.getFiles(currentUserId, model);
        MfoyouFileRet mfoyouFileRet = new MfoyouFileRet();
        mfoyouFileRet.setList(files);
        mfoyouFileRet.setBasUrl(image_server);
        return JsonRet.buildSuccRet(mfoyouFileRet);
    }

    @GET
    @Path(value = "/fileInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getFileInfo(@Context HttpServletRequest request, @QueryParam("ids") String ids) {
        if (ids.length() < 1) {
            return JsonRet.buildFailRet("参数错误", (List<HuawuFile>) null);
        }
        String[] params = ids.split(",");
        List<Integer> list = new ArrayList<>();
        for (String param : params) {
            list.add(Integer.parseInt(param));
        }
        MfoyouFileRet mfoyouFileRet = new MfoyouFileRet();
        mfoyouFileRet.setList(fileService.getFileInfos(list));
        mfoyouFileRet.setBasUrl(image_server);
        return JsonRet.buildSuccRet(mfoyouFileRet);
    }

    @GET
    @Path(value = "/fileServer")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> fileServer(@Context HttpServletRequest request) {
        return JsonRet.buildSuccRet(image_server);
    }


    /**
     * 获取用户分享图片
     *
     * @param type
     * @param productUrl
     * @param productPrice
     * @param productName
     * @param page
     * @param scene
     * @param appid
     * @return
     */
    @GET
    @Path(value = "/getWxSharePicture/{agentId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public void getWxSharePicture(@QueryParam("type") Integer type,
                                  @QueryParam("productUrl") String productUrl, @QueryParam("productPrice") String productPrice,
                                  @QueryParam("productName") String productName, @QueryParam("page") String page,
                                  @QueryParam("scene") String scene, @QueryParam("appid") String appid, @Context HttpServletResponse response, @PathParam("agentId") String agentstr) {
        logger.info("type=" + type);
        logger.info("productUrl=" + productUrl);
        logger.info("productPrice=" + productPrice);
        logger.info("productName=" + productName);
        logger.info("page=" + page);
        logger.info("scene=" + scene);
        logger.info("appid=" + appid);
        logger.info("agentstr=" + agentstr);
        try {
            if (type == null) {
                response.getWriter().print("type为空");
            }
            if (StringUtils.isEmpty(agentstr)) {
                response.getWriter().print("agentId为空");
            }
            if (StringUtils.isEmpty(productUrl)) {
                response.getWriter().print("产品图片为空");
            }
            if (StringUtils.isEmpty(productPrice)) {
                response.getWriter().print("商品价格为空");
            }
            if (StringUtils.isEmpty(productName)) {
                response.getWriter().print("商品名称为空");
            }
            if (StringUtils.isEmpty(page)) {
                response.getWriter().print("page为空");
            }
            if (StringUtils.isEmpty(scene)) {
                response.getWriter().print("scene为空");
            }
            if (StringUtils.isEmpty(appid)) {
                response.getWriter().print("appid为空");
            }
            BufferedImage wxSharePicture = fileService.getWxSharePicture(type, productUrl, productPrice, productName, page, scene, appid, agentstr);
            ImageIO.write(wxSharePicture, "png", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
